package com.ms.interceptor;

import com.ms.entity.Manager;
import com.ms.entity.Organizer;
import com.ms.utils.SimpleTokenUtils;
import com.ms.utils.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


@Component // 标记为Spring组件，方便后续注入到配置类
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求路径
        String requestURI = request.getRequestURI();
        
        // 对于用户注册和登录等公开接口，不需要token验证
        if (requestURI.contains("/api/user/register") || requestURI.contains("/api/user/login")
            || requestURI.contains("/manager/login") || requestURI.startsWith("/static/qua_app/")) {
            return true; // 直接放行
        }
        
        // 1. 从请求头获取token
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            response.setContentType("text/plain;charset=utf-8");
            response.getWriter().write("未登录，请先登录");
            return false;
        }

        // 2. 验证token并获取用户
        Object user = SimpleTokenUtils.getUserByToken(token);
        if (user == null) {
            response.setContentType("text/plain;charset=utf-8");
            response.getWriter().write("token无效或已过期");
            return false;
        }

        // 3. 存入ThreadLocal
        UserContext.setUser(user);
        return true;
    }

    // 请求结束后清除 ThreadLocal
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.remove(); // 清理ThreadLocal
    }
}